package com.coocaa.x.app.screenshot;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by luwei on 15-11-10.
 */
public class MainActivity extends Activity implements View.OnFocusChangeListener{

    private Button init = null;
    private Button auto = null;
    private Button manual = null;
    private Button command = null;
    private TextView tips = null;
    private PackageManager pm = null;
    private ApkInfo current = null;
    private static final int COUNT = 5;//截图次数
    private static final int DIVIDE = 10;//间隔,秒
    private static final String PATH = "/mnt/usb/sda4/screenshot";
    private List<ApkInfo> apkInfoList = new ArrayList<ApkInfo>();
    private static final String SCREEN_SHOT = "coocaa.intent.action.SCREEN_SHOT";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);
        init = (Button) findViewById(R.id.init);
        auto = (Button) findViewById(R.id.auto);
        manual = (Button) findViewById(R.id.manual);
        command = (Button)findViewById(R.id.command);
        tips = (TextView) findViewById(R.id.tips);
        init.setOnClickListener(clickListener);
        auto.setOnClickListener(clickListener);
        manual.setOnClickListener(clickListener);
        command.setOnClickListener(clickListener);
        init.setOnFocusChangeListener(this);
        auto.setOnFocusChangeListener(this);
        manual.setOnFocusChangeListener(this);
        command.setOnFocusChangeListener(this);
        pm = getPackageManager();
        copyScreenShotShell();
    }


    View.OnClickListener clickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (v.equals(init)) {
                initApkInfo();
            } else if (v.equals(auto)) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        String path = getFilesDir() + File.separator + SCREEN_SHOT_NAME;
                        for (ApkInfo param : apkInfoList) {
                            Log.i("screen", "begin screenshot " + param.name);
                            StringBuilder builder = new StringBuilder();
                            builder.append(" ").append(PATH).append(" ").append(param.fileName)
                                    .append(" ").append(param.name).append(" ").append(param.pkgName);
                            try {
                                Runtime.getRuntime().exec(path + builder.toString()).waitFor();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }).start();
            } else if (v.equals(manual)) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        for (ApkInfo info : apkInfoList){
                            screenShotManual(info);
                        }
                    }
                }).start();
            }else if(v.equals(command)){
                IntentFilter filter = new IntentFilter();
                filter.addAction(SCREEN_SHOT);
                registerReceiver(receiver, filter);
                if (apkInfoList.size() > 0){
                    current = apkInfoList.remove(0);
                    count = 0;
                    screenShotCommand(current);
                }
            }
        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        Log.i("screen", "the key is " + keyCode);
        return super.onKeyDown(keyCode, event);
    }

    private void initApkInfo() {
        File directory = new File(PATH);
        if (directory.isDirectory()) {
            File[] apkPath = directory.listFiles();
            for (File file : apkPath) {
                if (file.isFile()) {
                    String path = PATH + File.separator + file.getName();
                    Log.i("screen","the file path is " + path);
                    ApkInfo info = getApkInfo(path);
                    if (info == null)
                        continue;
                    File screenDireetory = new File(PATH + File.separator + info.name);
                    if (!screenDireetory.exists())
                        screenDireetory.mkdir();
                    info.fileName = file.getName();
                    apkInfoList.add(info);
                    tips.setText(path);
                }

            }
            tips.setText("总共有" + apkInfoList.size() + "个APK需要截图");
        }
    }

    private ApkInfo getApkInfo(String apkPath) {
        PackageInfo pkgInfo = pm.getPackageArchiveInfo(apkPath, PackageManager.GET_ACTIVITIES);
        if (pkgInfo != null) {
            ApplicationInfo appInfo = pkgInfo.applicationInfo;
            /* 必须加这两句，不然下面icon获取是default icon而不是应用包的icon */
            appInfo.sourceDir = apkPath;
            appInfo.publicSourceDir = apkPath;
            String appName = pm.getApplicationLabel(appInfo).toString();// 得到应用名
            String packageName = appInfo.packageName; // 得到包名
            ApkInfo back = new ApkInfo();
            back.name = appName.trim();
            back.pkgName = packageName;
            Log.i("screen", "the appname is " + appName + " and pname is " + packageName);
            return back;
        }
        return null;
    }

    public static final String SCREEN_SHOT_NAME = "screenshot.sh";

    private void copyScreenShotShell() {
        try {
            InputStream in = getAssets().open(SCREEN_SHOT_NAME);
            String path = getFilesDir() + File.separator + SCREEN_SHOT_NAME;
            File file = new File(path);
            if (file.exists())
                file.delete();
            FileOutputStream out = new FileOutputStream(file);
            byte[] buffer = new byte[2048];
            int count = 0;
            while (in.read(buffer) != -1) {
                out.write(buffer);
            }
            in.close();
            out.close();
            Runtime.getRuntime().exec("chmod 777 " + path);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void screenShotCommand(final ApkInfo info){
        tips.setText("正在安装" + info.name);
        new Thread(new Runnable() {
            @Override
            public void run() {
                exec("busybox mv " + PATH + File.separator
                        + info.fileName + " " + PATH + File.separator + info.name + File.separator);
                exec("pm install -r " + PATH + File.separator
                        + info.name + File.separator + info.fileName);
                sleep(3);
                Intent intent = getPackageManager().getLaunchIntentForPackage(info.pkgName);
                startActivity(intent);
            }
        }).start();
    }

    private void screenShotManual(ApkInfo info) {
        tips.setText("正在安装" + info.name);
        exec("busybox mv " + PATH + File.separator
                + info.fileName + " " + PATH + File.separator + info.name + File.separator);
        exec("pm install -r " + PATH + File.separator
                + info.name + File.separator + info.fileName);
        sleep(3);
        Intent intent = getPackageManager().getLaunchIntentForPackage(info.pkgName);
        startActivity(intent);
        sleep(3);
        for (int i = 1; i <= COUNT; i++) {
            sleep(DIVIDE);
            screenShot(info, i);
            final int j = i;
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(MainActivity.this, "已截图" + j + "张" + ",10秒后截图下一张", Toast.LENGTH_SHORT).show();
                }
            });

        }
        sleep(3);
        exec("pm uninstall " + info.pkgName);
    }

    private void screenShot(ApkInfo info, int i) {
        String screenPath = PATH + File.separator + info.name + File.separator + String.valueOf(i) + ".png";
        exec("screencap -p " + screenPath);
        convertPNGtoJPG(screenPath);
    }

    private void exec(String command) {
        try {
            Log.i("screen","command is " + command);
            Runtime.getRuntime().exec(command).waitFor();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void sleep(long time) {
        try {
            Thread.sleep(time * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private int count = 0;
    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(SCREEN_SHOT)){
                String params = intent.getStringExtra("command");
                if (params != null){
                    Log.i("screen","the brocast params is " + params);
                    if (params.equals("screenshot")){
                        if (current != null){
                            count++;
                            screenShot(current, count);
                            Toast.makeText(MainActivity.this, "已对" + current.name + "截图第" + count + "张", Toast.LENGTH_SHORT).show();
                        }
                    }else if(params.equals("next")){
                        if (current != null)
                            exec("pm uninstall " + current.pkgName);
                        if (apkInfoList.size() > 0){
                            current = apkInfoList.remove(0);
                            count = 0;
                            screenShotCommand(current);
                        }else{
                            tips.setText("所有应用已截图完毕");
                        }
                    }
                }
            }
        }
    };

    @Override
    protected void onDestroy() {
        try {
            unregisterReceiver(receiver);
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.onDestroy();
    }


    private void convertPNGtoJPG(String path){
        try {
            File file = new File(path);
            if (!file.exists())
                return;
            Bitmap bitmap = BitmapFactory.decodeFile(path);
            String outputPath = file.getPath().replace("png","jpg");
            int quality = 100;
            FileOutputStream fileOutStr = new FileOutputStream(outputPath);
            BufferedOutputStream bufOutStr = new BufferedOutputStream(
                    fileOutStr);
            bitmap.compress(Bitmap.CompressFormat.JPEG, quality, bufOutStr);
            bufOutStr.flush();
            bufOutStr.close();
            file.delete();
            Log.i("screen","convert " + path + " to " + outputPath);
        } catch (FileNotFoundException exception) {
            Log.e("debug_log", exception.toString());
        } catch (IOException exception) {
            Log.e("debug_log", exception.toString());
        }
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (v.equals(init)){
            tips.setText("初始化操作，解析特定目录下待截图的所有apk包");
        }else if(v.equals(auto)){
            tips.setText("全自动截图，截图效果最差，并可能存在很多异常问题");
        }else if(v.equals(manual)){
            tips.setText("手动操作应用，自动截图，启动应用后每过" + DIVIDE + "秒截图一次，截图" + COUNT + "次后自动切换到下一个应用");
        }else if(v.equals(command)){
            tips.setText("手动操作，手动截图，通过发送特定的action来截图和切换到下一个应用，效果最好");
        }
    }
}
